﻿using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Web.Hosting;
using System.Web.Management;
using Microsoft.ServiceHosting.ServiceRuntime;

namespace WASM.WebSite.Logic.Logging
{
	public class FlatFileEventProvider : WebEventProvider
	{
		private string _logFolder;
		private string _fileName;


		public FlatFileEventProvider()
			: base()
		{
		}

		public virtual string FlatFileFullPath
		{
			get
			{
				string virtualPath = String.Empty;
				if (Logger.HttpContext != null && Logger.HttpContext.Server != null)
				{
					virtualPath = Logger.HttpContext.Server.MapPath("~");
				}
				else if (HostingEnvironment.ApplicationHost != null)
				{
					virtualPath = HostingEnvironment.MapPath("~");
				}
				else
				{
					Assembly currAssembly = Assembly.GetExecutingAssembly();
					string assemblyPath = currAssembly.Location;
					virtualPath = Path.GetDirectoryName(assemblyPath);
				}

				string logFolderPath = virtualPath + _logFolder;
				if (!Directory.Exists(logFolderPath))
				{
					Directory.CreateDirectory(logFolderPath);
				}

				string fullPath = Path.Combine(virtualPath, _logFolder);

				DateTime currentDateTime = DateTime.Now;
				string fileName = String.Format("{0}_{1}_{2}_{3}.txt", _fileName, currentDateTime.Year, currentDateTime.Month, currentDateTime.Day); ;

				string fullFilePath = Path.Combine(fullPath, fileName);
				return fullFilePath;
			}
		}

		public override void Initialize(string name, NameValueCollection config)
		{
			base.Initialize(name, config);

			_fileName = config.Get("FileName");
			_logFolder = config.Get("LogFolder");

			if (String.IsNullOrEmpty(_fileName))
				throw new ConfigurationErrorsException("FileName is Required for FlatFileEventProvider.");

			if (String.IsNullOrEmpty(_logFolder))
				throw new ConfigurationErrorsException("LogFolder is Required for FlatFileEventProvider.");
		}

		public override void ProcessEvent(WebBaseEvent webEvent)
		{
			try
			{
				string logMessage = webEvent.ToString();

				using (FileStream fileStream = new FileStream(FlatFileFullPath, FileMode.OpenOrCreate | FileMode.Append,
					 FileAccess.Write, FileShare.Write))
				{
					using (StreamWriter writer = new StreamWriter(fileStream))
					{
						writer.Write(logMessage);
					}
				}
			}
			catch (Exception ex)
			{
				RoleManager.WriteToLog("Critical", "In the FlatFileEventProvider of exception occurred - " + ex.ToString());
			}
		}

		public override void Shutdown() { }

		public override void Flush() { }
	}
}
